const sounds: Record<string, ArrayBuffer> = {};
const soundBuffers: Record<string, AudioBuffer> = {};
let audioContext: AudioContext;
export function registerSound(name: string, sound: string) {
	const data = atob(sound);
	const buffer = new Uint8Array(data.length);
	for (let i = 0; i < buffer.byteLength; i++) {
		buffer[i] = data.charCodeAt(i);
	}
	sounds[name] = buffer.buffer;
}

function playBuffer(buffer: AudioBuffer) {
	const sourceBuffer = new AudioBufferSourceNode(audioContext);
	sourceBuffer.buffer = buffer;
	sourceBuffer.connect(audioContext.destination);
	sourceBuffer.start();
}

export function play(name: string) {
	if (!audioContext) {
		audioContext = new AudioContext();
	}
	const soundBuffer = soundBuffers[name];
	if (soundBuffer) {
		playBuffer(soundBuffer);
	} else {
		const soundData = sounds[name];
		if (soundData) {
			audioContext
				.decodeAudioData(soundData)
				.then((decoded) => {
					soundBuffers[name] = decoded;
					playBuffer(decoded);
				})
				.catch((reason) => {
					console.log(reason + '');
				});
		}
	}
}
